package com.faner4cloud.yun.controller;

import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import com.google.common.cache.CacheBuilder;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @author ...zz
 * @version v1
 * @summary 本地缓存-多重缓存问题
 * @since 2022/5/18 3:03 PM
 */
@Api(value = "caffeine", tags = "多重缓存问题")
@ApiSupport(order = 1)
@Slf4j
@RestController
@RequiredArgsConstructor
public class CaffeineController {



	private final LoadingCache<String, String> bannerCache = Caffeine.newBuilder()
		.refreshAfterWrite(1, TimeUnit.MINUTES)
		.expireAfterWrite(5, TimeUnit.MINUTES)
		.maximumSize(10)
		.build(key -> "1");

//	private final LoadingCache<String, List<SalePercent>> salePercentCache = CacheBuilder.newBuilder()
//		.maximumSize(100)
//		.expireAfterWrite(15, TimeUnit.SECONDS)
//		.refreshAfterWrite(10, TimeUnit.SECONDS)
//		.build(new CacheLoader<String, List<SalePercent>>() {
//			@Override
//			public List<SalePercent> load(String key) throws Exception {
//				return loadSalePercent(key);
//			}
//		});

	@Cacheable(key = "'cache_user_id_' + #id", value = "userIdCache", cacheManager = "cacheManager", sync = true)
	@GetMapping("/v1/caffeine/id")
	public long get(@RequestParam long id) {
		return id;
	}

	@Cacheable(key = "'cache_user_name_' + #name", value = "userNameCache", cacheManager = "cacheManager")
	@GetMapping("/v1/caffeine/name")
	public String get(@RequestParam String name) {
		return name;
	}

//	@CachePut(key = "'cache_user_id_' + #id", value = "userIdCache", cacheManager = "cacheManager")
//	@GetMapping("/v1/caffeine/name")
//	public long update(@RequestParam long id) {
//		return id;
//	}
//
//	@CacheEvict(key = "'cache_user_id_' + #id", value = "userIdCache", cacheManager = "cacheManager")
//	public void delete(long id) {
//		log.info("delete from db");
//	}

	@Cacheable(value = "userIdCache", key = "'cache_user_id_' + #a", cacheManager = "cacheManager")
	@GetMapping("/v1/caffeine/one")
	public String one(@RequestParam String a) {
//		return bannerCache.get(a);
		return a;
	}
}
